package com.nari.ncps.screen.service.impl.ne;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.ne.NeOpermonWindState;
import com.nari.ncps.screen.mapper.ne.NeOpermonPvStateMapper;
import com.nari.ncps.screen.service.ne.NeOpermonPvStateService;
import com.nari.ncps.screen.vo.ne.NePvEquipmentStatusVO;
import com.nari.ncps.screen.entity.ne.NeOpermonPvState;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

/**
 * <p>
 * 光伏设备状态监测表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class NeOpermonPvStateServiceImpl extends ServiceImpl<NeOpermonPvStateMapper, NeOpermonPvState> implements NeOpermonPvStateService {

    @Override
    public NePvEquipmentStatusVO getPvEquipmentStatus(Integer year) {
        // 如果没有指定年份，使用当前年份
        if (year == null) {
            year = LocalDate.now().getYear();
        }
        
        // 查询指定年份的最新数据
        LambdaQueryWrapper<NeOpermonPvState> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NeOpermonPvState::getOrgCode, "100360")
                .eq(NeOpermonPvState::getDelFlag, 0);
        queryWrapper.orderByDesc(NeOpermonPvState::getMonth);
        queryWrapper.last("LIMIT 1");
        
        NeOpermonPvState entity = this.getOne(queryWrapper);
        
        // 构建返回VO
        NePvEquipmentStatusVO vo = new NePvEquipmentStatusVO();
        if (entity != null) {
            vo.setNormalCombinerBoxes(entity.getNormalCombinerBoxes());
            vo.setNormalTransformers(entity.getNormalTransformers());
            vo.setFaultyInverters(entity.getFaultyInverters());
            vo.setUnknownTransformers(entity.getUnknownTransformers());
            vo.setUnknownInverters(entity.getUnknownInverters());
            
            // 计算其他数量 = 总数 - 已统计的各类数量
            Integer total = entity.getTotalPvUnits();
            if (total != null) {
//                其他=逆变器台数-逆变器正常运行台数-逆变器通汛故障台数-逆变器故障停机台数-逆变器限功率运行台数-逆变器环境停机台数
                int counted = (entity.getNormalCombinerBoxes() != null ? entity.getNormalCombinerBoxes() : 0)
                        + (entity.getNormalTransformers() != null ? entity.getNormalTransformers() : 0)
                        + (entity.getFaultyInverters() != null ? entity.getFaultyInverters() : 0)
                        + (entity.getUnknownTransformers() != null ? entity.getUnknownTransformers() : 0)
                        + (entity.getUnknownInverters() != null ? entity.getUnknownInverters() : 0);
                vo.setOther(total - counted);
            }
        }
        
        return vo;
    }

}
